﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecipeBookBusiness
{
    public class Ingredient
    {
        private RecipeBookEntities _entities = new RecipeBookEntities();
        private int _id;
        private string _description;

        public Ingredient(int ingredientID)
        {
            loadIngredientClass(ingredientID);
        }

        public Ingredient(string description)
        {
            try
            {
                IngredientDataRow idr = new IngredientDataRow();
                idr.Description = description;

                //Save to DB and get ID
                _entities.AddToIngredientDataRowSet(idr);
                _entities.SaveChanges();
                int newIngredientID = 0;
                foreach (IngredientDataRow idIdr in _entities.IngredientDataRowSet)
                {
                    if (idIdr.ID > newIngredientID)
                        newIngredientID = idIdr.ID;
                }
                loadIngredientClass(newIngredientID);
            }
            catch (Exception ex)
            {
                //TODO: Real exception handling
                Console.Write(ex.Message);
            }
        }

        public void UpdateIngredient(string description)
        {
            IngredientDataRow ingredientDR = (from c in _entities.IngredientDataRowSet
                                          where c.ID == _id
                                          select c).FirstOrDefault();
            bool needToUpdate = false;
            if (!_description.Equals(description))
            {
                _description = description;
                needToUpdate = true;
            }

            if (needToUpdate)
            {
                ingredientDR.Description = _description;
                _entities.SaveChanges();
            }
        }

        public void DeleteIngredient()
        {
            IngredientDataRow idr = (from c in _entities.IngredientDataRowSet
                                 where c.ID == _id
                                 select c).FirstOrDefault();
            _entities.DeleteObject(idr);
            _entities.SaveChanges();
        }

        private void loadIngredientClass(int ingredientID)
        {
            IngredientDataRow ingredientDR = (from c in _entities.IngredientDataRowSet
                                      where c.ID == ingredientID
                                      select c).FirstOrDefault();
            _id = ingredientDR.ID;
            _description = ingredientDR.Description;
        }

        public int ID
        {
            get
            {
                return _id;
            }
        }

        public string Description
        {
            get
            {
                return _description;
            }
        }
    }
}
